package com.hanyi.web.controller.system;

import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.Set;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.net.NetUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;
import com.hanyi.common.helper.LoginHelper;
import com.hanyi.system.domain.*;
import com.hanyi.system.domain.bo.SysFaceAttrBo;
import com.hanyi.system.domain.bo.SysPersonAttrBo;
import com.hanyi.system.domain.bo.SysVehicleAttrBo;
import com.hanyi.system.domain.vo.SysLocalTaskVo;
import com.hanyi.system.domain.vo.SysOfflineTaskVo;
import com.hanyi.system.domain.vo.SysRealtimeTaskVo;
import com.hanyi.system.service.*;
import com.hanyi.thirdparty.AddChannelRequest;
import com.hanyi.thirdparty.BaseResponse;
import com.hanyi.thirdparty.domain.AnalysisAttribute;
import com.hanyi.thirdparty.domain.AnalysisData;
import com.hanyi.thirdparty.domain.AnalysisResult;
import com.hanyi.thirdparty.domain.TargetType;
import com.hanyi.thirdparty.service.IAlgorithmService;
import lombok.RequiredArgsConstructor;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.hanyi.common.annotation.RepeatSubmit;
import com.hanyi.common.annotation.Log;
import com.hanyi.common.core.controller.BaseController;
import com.hanyi.common.core.domain.PageQuery;
import com.hanyi.common.core.domain.R;
import com.hanyi.common.core.validate.AddGroup;
import com.hanyi.common.core.validate.EditGroup;
import com.hanyi.common.enums.BusinessType;
import com.hanyi.common.utils.poi.ExcelUtil;
import com.hanyi.system.domain.vo.SysAnalysisResultVo;
import com.hanyi.system.domain.bo.SysAnalysisResultBo;
import com.hanyi.common.core.page.TableDataInfo;

/**
 * 任务结果
 *
 * @author grantfee
 * @date 2023-11-06
 */

@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/analysisResult")
public class SysAnalysisResultController extends BaseController {

    private final ISysRealtimeTaskService iSysRealtimeTaskService;
    private final ISysLocalTaskService iSysLocalTaskService;
    private final ISysOfflineTaskService iSysOfflineTaskService;

    private final ISysAnalysisResultService iSysAnalysisResultService;
    private final IAlgorithmService iAlgorithmService;

    private final ISysPersonAttrService iSysPersonAttrService;
    private final ISysFaceAttrService iSysFaceAttrService;
    private final ISysVehicleAttrService iSysVehicleAttrService;

    /**
     * 查询任务结果列表
     */
    @SaCheckPermission("system:analysisResult:list")
    @GetMapping("/list")
    public TableDataInfo<SysAnalysisResultVo> list(SysAnalysisResultBo bo, PageQuery pageQuery) {
        log.info("list query :"+bo);
        return iSysAnalysisResultService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出任务结果列表
     */
    @SaCheckPermission("system:analysisResult:export")
    @Log(title = "任务结果", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SysAnalysisResultBo bo, HttpServletResponse response) {
        List<SysAnalysisResultVo> list = iSysAnalysisResultService.queryList(bo);
        ExcelUtil.exportExcel(list, "任务结果", SysAnalysisResultVo.class, response);
    }

    /**
     * 获取任务结果详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("system:analysisResult:query")
    @GetMapping("/{id}")
    public R<SysAnalysisResultVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iSysAnalysisResultService.queryById(id));
    }

    /**
     * 新增任务结果
     */
    @SaCheckPermission("system:analysisResult:add")
    @Log(title = "任务结果", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SysAnalysisResultBo bo) {

        return toAjax(iSysAnalysisResultService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改任务结果
     */
    @SaCheckPermission("system:analysisResult:edit")
    @Log(title = "任务结果", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysAnalysisResultBo bo) {
        return toAjax(iSysAnalysisResultService.updateByBo(bo) ? 1 : 0);
    }


    /**
     * 删除任务结果
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:analysisResult:remove")
    @Log(title = "任务结果", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iSysAnalysisResultService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }

    @SaIgnore
    @RequestMapping("/event/meta/{id}")
    public BaseResponse receiveMetaData(@PathVariable("id") long terminalId ){
        log.info("receive json meta data:"+terminalId);
        return null;
    }

    private static String DOWNLOAD_PRE_URL="http://192.168.2.100:9000";
    @PostConstruct
    public void init(){
        String profile = SpringUtil.getActiveProfile();
        if(profile.equals("prod")){
            String externalIp = "127.0.0.1";
            Set<String> hostIPs =  NetUtil.localIps();
            NetworkInterface networkInterface =  NetUtil.getNetworkInterface("eth0");
            List<InterfaceAddress> list= networkInterface.getInterfaceAddresses();
            for(InterfaceAddress interfaceAddress :list){
                String host  = interfaceAddress.getAddress().getHostAddress();
                log.info("local host ip:"+host);
                if(host.contains("eth0")){
                    continue;
                }
                externalIp = host;
            }

            DOWNLOAD_PRE_URL="http://"+externalIp+":9000";
            log.info("image download pre url:"+DOWNLOAD_PRE_URL);
        }else{
            DOWNLOAD_PRE_URL="http://192.168.2.100:9000";
            log.info("image download pre url:"+DOWNLOAD_PRE_URL);
        }
    }
    @SaIgnore
    @RequestMapping("/event/result")
    public BaseResponse eventResult(@RequestBody String result ){
        //log.info("eventResult : "+result);
        long deptId = 0;
        long taskId = 0;
        Date date = new Date();
        SysAnalysisResultBo bo = new SysAnalysisResultBo();
        bo.setDeptId(deptId);
        bo.setEventStartTime(date);
        bo.setEventEndTime(date);
        bo.setPersonCount(0L);

        List<AnalysisAttribute> attributes=null;

        Gson gson = new Gson();
        AnalysisResult event = gson.fromJson(result, AnalysisResult.class);
        if(event.getData()!=null){
            List<AnalysisData> list = event.getData();
            for(AnalysisData data:list){
                int type = data.getType();
                if(type==0){
                    taskId = Long.parseLong(data.getTask_id());
                    bo.setTaskId(taskId);

                    int channelId = data.getChannel_id();
                    String cropImageData = data.getCrop_image_data();
                    String fullImageData = data.getFull_image_data();

                    bo.setCaptureImageUrl(cropImageData);
                    bo.setFullImageUrl(fullImageData);
                    log.info("image download url:"+bo.getCaptureImageUrl());
                    List<AnalysisData.Result.AlgResult> algResultList =  data.getResult().getAlg_results();
                    if(algResultList!=null){
                        for(AnalysisData.Result.AlgResult algResult : algResultList){
                            List<AnalysisData.Result.AlgResult.AlgResultObjects> algResultObjects = algResult.getObjects();
                            for(AnalysisData.Result.AlgResult.AlgResultObjects algResultObj:algResultObjects){
                                //log.info("target type:"+algResultObj.getType() );
                                attributes = algResultObj.getAttributes();
                                if(algResultObj.getType() == TargetType.PERSON_CLS){//行人
                                    bo.setEventType("0");
                                }else if(algResultObj.getType() == TargetType.VEHICLE_CAR_CLS){//轿车
                                    bo.setEventType("1");
                                }else if(algResultObj.getType() == TargetType.VEHICLE_BUS_CLS){//巴士
                                    bo.setEventType("1");
                                }else if(algResultObj.getType() == TargetType.VEHICLE_TRUCK_CLS){//卡车
                                    bo.setEventType("1");
                                }else if(algResultObj.getType() == TargetType.VEHICLE_MINANBAO_CLS){//面包
                                    bo.setEventType("1");
                                }else if(algResultObj.getType() == TargetType.FACE_CLS){//人脸
                                    bo.setEventType("2");
                                }
                            }
                        }
                    }

                }
            }
        }

        if(taskId!=0){//设置任务信息
            SysRealtimeTask realtimeTaskVo =  iSysRealtimeTaskService.queryByTaskId(taskId);
            if(realtimeTaskVo != null){
                bo.setTaskName(realtimeTaskVo.getName());
                bo.setTaskType("0");
                bo.setDeptId(realtimeTaskVo.getDeptId());
            }else{
                SysLocalTask localTaskVo = iSysLocalTaskService.queryByTaskId(taskId);
                if(localTaskVo!=null){
                    bo.setTaskName(localTaskVo.getName());
                    bo.setTaskType("2");
                    bo.setDeptId(localTaskVo.getDeptId());
                }else{
                    SysOfflineTask offlineTaskVo = iSysOfflineTaskService.queryByTaskId(taskId);
                    if(offlineTaskVo!=null){
                        bo.setTaskName(offlineTaskVo.getName());
                        bo.setTaskType("1");
                        bo.setDeptId(offlineTaskVo.getDeptId());
                    }
                }
            }
        }

        boolean ok = iSysAnalysisResultService.insertByBo(bo);
        log.info("insert analysis result, event id:"+bo.getId());

        if(attributes!=null&& bo.getEventType()!=null){
            if(bo.getEventType().equals("0")){//行人
                SysPersonAttrBo personAttr = new SysPersonAttrBo();
                for(AnalysisAttribute attribute:attributes){
                    if(attribute.getAttribute()==null ||attribute.getAttribute().getAttr_name()==null){
                        continue;
                    }
                    //log.info("get attr:"+attribute.getAttribute().getAttr_name());
                    if(attribute.getAttribute().getAttr_name().equals("age")){
                        personAttr.setAge(attribute.getAttribute().getText());
                        personAttr.setAgeScore(attribute.getAttribute().getScore());
                    }else if(attribute.getAttribute().getAttr_name().equals("gender")){
                        personAttr.setGender(attribute.getAttribute().getText());
                        personAttr.setGenderScore(attribute.getAttribute().getScore());
                    } else if(attribute.getAttribute().getAttr_name().equals("upper_color")){
                        personAttr.setUpperColor(attribute.getAttribute().getText());
                        personAttr.setUpperColorScore(attribute.getAttribute().getScore());
                    }else if(attribute.getAttribute().getAttr_name().equals("bottom_color")){
                        personAttr.setBottomColor(attribute.getAttribute().getText());
                        personAttr.setBottomColorScore(attribute.getAttribute().getScore());
                    }else if(attribute.getAttribute().getAttr_name().equals("hair")){
                        personAttr.setHair(attribute.getAttribute().getText());
                        personAttr.setHairScore(attribute.getAttribute().getScore());
                    }else if(attribute.getAttribute().getAttr_name().equals("hat")){
                        personAttr.setHat(attribute.getAttribute().getText());
                        personAttr.setHatScore(attribute.getAttribute().getScore());
                    }else if(attribute.getAttribute().getAttr_name().equals("upper_type")){
                        personAttr.setUpperType(attribute.getAttribute().getText());
                        personAttr.setUpperTypeScore(attribute.getAttribute().getScore());
                    }else if(attribute.getAttribute().getAttr_name().equals("bottom_type")){
                        personAttr.setBottomType(attribute.getAttribute().getText());
                        personAttr.setBottomTypeScore(attribute.getAttribute().getScore());
                    }else if(attribute.getAttribute().getAttr_name().equals("mask")){
                        personAttr.setMask(attribute.getAttribute().getText());
                        personAttr.setMaskScore(attribute.getAttribute().getScore());
                    }else if(attribute.getAttribute().getAttr_name().equals("glasses")){
                        personAttr.setGlass(attribute.getAttribute().getText());
                        personAttr.setGlassScore(attribute.getAttribute().getScore());
                    }
                }
                personAttr.setResultId(bo.getId());
                iSysPersonAttrService.insertByBo(personAttr);
            }else if(bo.getEventType().equals("1")){//车辆
                SysVehicleAttrBo vehicleAttrBo = new SysVehicleAttrBo();
                vehicleAttrBo.setResultId(bo.getId());
                for(AnalysisAttribute attribute:attributes){
                    if(attribute.getAttribute()==null){
                        continue;
                    }
                    //log.info("get attr:"+attribute.getAttribute().getAttr_name());
                    if(attribute.getAttribute_type().equals("PlateResult")){
                        log.info("license:"+attribute.getAttribute().getLicence());
                        vehicleAttrBo.setLicense(attribute.getAttribute().getLicence());
                        vehicleAttrBo.setLicenseScore(attribute.getAttribute().getLicence_score());
                    }else if(attribute.getAttribute_type().equals("BaseResult")){
                        if(attribute.getAttribute().getAttr_name().equals("color")){
                            vehicleAttrBo.setColor(attribute.getAttribute().getText());
                            vehicleAttrBo.setColorScore(attribute.getAttribute().getScore());
                        }else if(attribute.getAttribute().getAttr_name().equals("category")){
                            vehicleAttrBo.setVehicleType(attribute.getAttribute().getText());
                            vehicleAttrBo.setVehicleTypeScore(attribute.getAttribute().getScore());
                        }else if(attribute.getAttribute().getAttr_name().equals("brand")){
                            vehicleAttrBo.setBrand(attribute.getAttribute().getText());
                            vehicleAttrBo.setBrandScore(attribute.getAttribute().getScore());
                        }
                    }

                }

                iSysVehicleAttrService.insertByBo(vehicleAttrBo);

            }else if(bo.getEventType().equals("2")){//人脸
                SysFaceAttrBo faceAttrBo = new SysFaceAttrBo();
                faceAttrBo.setResultId(bo.getId());
                for(AnalysisAttribute attribute:attributes){
                    if(attribute.getAttribute().getAttr_name().equals("age")){
                        faceAttrBo.setAge(attribute.getAttribute().getText());
                        faceAttrBo.setAgeScore(attribute.getAttribute().getScore());
                    }else if(attribute.getAttribute().getAttr_name().equals("gender")){
                        faceAttrBo.setGender(attribute.getAttribute().getText());
                        faceAttrBo.setGenderScore(attribute.getAttribute().getScore());
                    }else if(attribute.getAttribute().getAttr_name().equals("hair")){
                        faceAttrBo.setHair(attribute.getAttribute().getText());
                        faceAttrBo.setHairScore(attribute.getAttribute().getScore());
                    }else if(attribute.getAttribute().getAttr_name().equals("hat")){
                        faceAttrBo.setHat(attribute.getAttribute().getText());
                        faceAttrBo.setHatScore(attribute.getAttribute().getScore());
                    }else if(attribute.getAttribute().getAttr_name().equals("glasses")){
                        faceAttrBo.setGlass(attribute.getAttribute().getText());
                        faceAttrBo.setGlassScore(attribute.getAttribute().getScore());
                    }else if(attribute.getAttribute().getAttr_name().equals("mask")){
                        faceAttrBo.setMask(attribute.getAttribute().getText());
                        faceAttrBo.setMaskScore(attribute.getAttribute().getScore());
                    }
                }

                iSysFaceAttrService.insertByBo(faceAttrBo);

            }
        }

        BaseResponse resp = new BaseResponse();
        resp.setCode(0);
        resp.setMessage("success");
        return resp;
    }
}
